package com.cakin;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class CookieDemo01 extends HttpServlet {
    /**
     * 功能描述：服务器告诉你，你来的时间，把这个时间封装未一个信件，你下次带来，我就知道你来了
     *
     * @param req  请求
     * @param resp 响应
     * @author cakin
     * @date 2020/6/9
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        PrintWriter out = resp.getWriter();
        // 服务端从客户端获取Cookie,返回的是数组，说明cookie可以返回多个
        Cookie[] cookies = req.getCookies();
        // 判断cookie是否存在
        if (cookies != null) {
            // 拿到前端送过来的cookie
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals("lastLoginTime")) {
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write("上次访问的时间是：" + date.toLocaleString());
                }
            }
        } else {
            out.write("你是第一次来");
        }

        // 服务端给客户端cookie
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
        cookie.setMaxAge(24 * 60 * 60);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
